import React from 'react';
import { connect } from 'react-redux';
import menuRoute from 'routes/menuRoute';
import moment from 'moment';
import { Form, Button, message, Spin, Modal, Tooltip, Icon } from 'antd';
import Chooser from 'components/chooser';
import baseService from 'share/base.service';
import chooserData from 'share/chooserData';
import expenseReportService from 'containers/expense-report/expense-report.service';
import customField from 'share/customField';
import { messages, deepFullCopy, deepCopy } from 'share/common';
import 'styles/expense-report/new-expense-report.scss';
import requestService from 'containers/request/request.service';
import errorMessage from 'share/errorMessage';

const FormItem = Form.Item;
let isClearStatus = false;
let newExpenseReportThis;
let firstInitLoad;
const { confirm } = Modal;

class NewExpenseReport extends React.Component {
  constructor(props) {
    super(props);
    newExpenseReportThis = this;
    firstInitLoad = false;
    // let expenseReportDetailUrl = menuRoute.getRouteItem('expense-report-detail').url
    // if (props.route.path.includes('union-expense-report')) {
    //   expenseReportDetailUrl = menuRoute.getRouteItem('union-expense-report-detail').url
    // }
    // console.log('expenseReportDetailUrl====',expenseReportDetailUrl)
    this.state = {
      loading: true,
      submitting: false,
      signEnable: false,
      formDetail: {},
      formDefaultValue: [], // 表单默认值
      approvalAddSignScope: [], // 加签人列表
      isMultiApplication: false, // 是否可以关联多申请单
      requestParticipant: [], // 关联申请单带入的参与人
      expenseReport: deepFullCopy(props.params.expenseReport),
      isInitDefaultValue: false, // 是否在初始化默认值，若为true，则不触发formItemChange方法，bug 32149
      contractParams: { // 获取合同的参数
        companyOID: props.company.companyOID,
        currency: props.company.baseCurrency
      },
      associationContract: {},
      jobInfo: props.params.jobInfo || {},
      companyInfo: {},
      hasChange: false,
      // expenseReportDetailUrl,
      hasChangeCompanyAndDepart: false
    };
  }

  // 处理代理单据逻辑
  dealProxies(usersOID) {
    baseService.changeLoginInfo(usersOID).then(() => {
    }).catch((err) => {
      location.href = '/';
      message.error(messages('expense-parent-report.key60'/* 哦呼，服务器出了点问题，请联系管理员或稍后再试:(*/));
    });
  }

  componentDidMount() {
    this.setState({ hasChange: true });
  }

  componentWillMount() {
    const { user } = this.props;
    const { formId, formDetail, userOID, applicationOID, applicantJobId } = this.props.params;
    isClearStatus = false;
    this.isCounterSignEnable(formId || formDetail.formOID, applicantJobId);
    if (formId && userOID && userOID !== ':userOID' && userOID !== user.userOID) {
      this.dealProxies(userOID);
      console.log('userOID', userOID)
    }
    if (formDetail) {
      this.setState({ formDetail, loading: false });
    } else {
      this.setState({ loading: true });
      baseService.getFormDetail(formId).then((res) => {
        this.setState({ formDetail: res.data }, this.getFormDefaultValue);
      });
      this.checkRelatedApplication();
    }

    if (applicationOID && applicationOID !== ':applicationOID') { // 申请单跳入报销单
      requestService.getRequestDetail(applicationOID)
        .then((res) => {
          this.props.form.setFieldsValue({ application: [res.data] });
          this.handleChangeApplication([res.data]);
        })
        .catch((err) => {
          errorMessage(err.response);
        });
    }
    // 新建报销单时获取岗位信息
    this.getJobInfo();
    // 新建报销单时获取费用承担公司列表
    this.getCompanies();
  }

  // 获取表单默认值
  getFormDefaultValue = (userOID = this.props.user.userOID) => {
    const { formId, applicantJobId, proxy } = this.props.params;
    const { formDetail, expenseReport } = this.state;
    const { contractParams } = this.state;
    const jobId = applicantJobId === ':applicantJobId' ? undefined : applicantJobId;
    if (proxy === '1') { // 代提报销单，表单的默认数据要根据被代理人的userOID去获取
      userOID = this.props.params.userOID
    }
    expenseReportService.getFormValue(userOID, formId, jobId).then((res) => {
      let customFormFields = formDetail.customFormFields || [];
      if (expenseReport) {
        customFormFields = expenseReport.custFormValues || customFormFields;
      }
      customFormFields.forEach((field) => {
        res.data.forEach((item) => {
          if (field.messageKey === 'select_company' && item.fieldOID === field.fieldOID) {
            contractParams.companyOID = item.value;
          }
        });
      });
      this.setState({
        contractParams,
        loading: false,
        formDefaultValue: res.data
      });
    });
  };

  // 获取滚动元素相对元素对象
  getPopupContainer = () => this.refs.newExpenseReport;

  // 处理是否启用时间
  processEnableTime = (field) => {
    let enableTime = false;
    if (field.fieldConstraint && JSON.parse(field.fieldConstraint) && JSON.parse(field.fieldConstraint).enableTime) {
      enableTime = true;
    }
    return enableTime;
  };

  // 处理启用时间默认值
  processDefaultTime = (field) => {
    let defaultTime = null;
    if (field.fieldConstraint && JSON.parse(field.fieldConstraint)) {
      if (JSON.parse(field.fieldConstraint).defaultTime) {
        defaultTime = moment(moment(JSON.parse(field.fieldConstraint).defaultTime).format('HH:mm'), 'HH:mm');
      } else {
        if (field.messageKey === 'start_date') {
          defaultTime = moment('00:00', 'HH:mm');
        }
        if (field.messageKey === 'end_date') {
          defaultTime = moment('23:59', 'HH:mm');
        }
      }
    }
    return defaultTime;
  };

  // 获取岗位详情
  getJobInfo = () => {
    const { applicantJobId } = this.props.params;
    console.log(applicantJobId)
    if (applicantJobId !== ':applicantJobId') {
      applicantJobId && expenseReportService.getJobInfo(applicantJobId).then((res) => {
        this.setState({ jobInfo: res.data || {} });
      });
    }
  };

  // 当“是否显示关联”组件的switch的状态发生变化时触发
  onSwitchChange = (field, isSwitchOn) => {
    const { form } = this.props;
    const map = item => {
      if (item.fieldOID === field.fieldOID) {
        return {
          ...item,
          isSwitchOn
        }
      }
      return item
    }
    
    this.setState({
      formDetail: {
        ...this.state.formDetail,
        customFormFields: (this.state.formDetail.customFormFields||[]).map(map)
      },
      expenseReport: {
        ...this.state.expenseReport,
        custFormValues: (this.state.expenseReport.custFormValues||[]).map(map)
      }
    }, () =>{ 
      form.validateFields([field.fieldOID], { force: true });
    })
  }

  renderFormItem = () => {
    const { getFieldDecorator, getFieldsValue } = this.props.form;
    const { applicantJobId } = this.props.params;
    const { formDefaultValue, expenseReport, jobInfo } = this.state;
    let formDetail = deepFullCopy(this.state.formDetail)
    const { companyOID, departmentOID } = jobInfo;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: !expenseReport ? 10 : 14, offset: 1 },
    };
    let customFormFields = deepFullCopy(formDetail.customFormFields || []);
    if (expenseReport) {
      /**
       * 代提报销单，编辑报销单的时候所有信息都以费用确认人的userOID为准
       * 保存时申请人OID依旧是秘书
       */
      if (expenseReport.formCode === 'BX006') {
        expenseReport.realApplicantOID = this.props.user.userOID
        expenseReport.custFormValues.some((field) => {
          if (field.messageKey === 'select_user') {
            expenseReport.applicantOID = field.value
            return true;
          }
        })
      }
      customFormFields = deepFullCopy(expenseReport.custFormValues || customFormFields);
      if (formDetail.customFormFields) {
        let tempCustomFormFields = formDetail.customFormFields.map((item) => {
          let result = {}
          customFormFields.map((field) => {
            if (item.fieldOID === field.fieldOID) {
              result = Object.assign({}, {...item}, {...field})
            }
          })
          return result
        })
        formDetail.customFormFields = deepFullCopy(tempCustomFormFields)
        customFormFields = formDetail.customFormFields
      } else {
      formDetail.customFormFields = customFormFields;
      }
    }
    customFormFields.length > 0 && customFormFields.sort((a, b) => a.sequence > b.sequence || -1);
    return customFormFields.map((field) => {
      const switchMessageKey = ['switch', 'writeoff_flag'];
      const option = {
        valuePropName: ~switchMessageKey.indexOf(field.messageKey) ? 'checked' : 'value',
        rules: []
      };
      let fieldNameHelp = '';
      // 表单默认值
      let fieldDefaultValue = {};
      formDefaultValue.map((item) => {
        item.fieldOID === field.fieldOID && (fieldDefaultValue = item);
      });
      if (expenseReport) {
        option.initialValue = customField.getInitialValue(field);
        const fieldConstraint = field.fieldConstraint ? JSON.parse(field.fieldConstraint) : {};
        if (field.messageKey === 'select_company' && fieldConstraint.unionCompany) {
          if (option.initialValue) {
            const tempObj = Object.assign({}, option.initialValue);
            option.initialValue = [{ companyOID: tempObj.key, name: tempObj.label }];
          } else {
            option.initialValue = [];
          }
        }
      } else {
        option.initialValue = customField.getDefaultValue(field, fieldDefaultValue, formDetail.formCode);
      }
      // 开始结束日期以组合组件range_picker显示
      if (field.messageKey === 'start_date') {
        // 开始结束日期都有值时，该组件才有值
        field.value && customFormFields.map((fieldItem) => {
          if (fieldItem.messageKey === 'end_date' && fieldItem.value) {
            option.initialValue = [moment(field.value), moment(fieldItem.value)];
          }
        });
        // 开始结束日期都启用时间时，该组件才启用时间
        if (this.processEnableTime(field)) {
          field.defaultValueTime = [];
          field.defaultValueTime.push(this.processDefaultTime(field));
          customFormFields.map((fieldItem) => {
            if (fieldItem.messageKey === 'end_date' && this.processEnableTime(fieldItem)) {
              field.defaultValueTime.push(this.processDefaultTime(fieldItem));
              field.enableTime = true;
            }
          });
        }
        field.messageKey = 'range_picker';
        field.fieldName = messages('expense-parent-report.key214')/* 开始结束日期*/;
      }
      if (['public.assembly'].includes(field.messageKey)) { // 是公用列表
        if (field.isHidden) { // 展示“是否显示联动开关”
          if (field.isSwitchOn) { // 联动开关为true
            if (field.required) { // 设置了这个表单项必填
              option.rules.push({
                required: true,
                message: messages('common.name.is.required', { name: field.fieldName })  // ${field.fieldName}必填)
              });
              option.rules.push({
                validator: (rule, value, callback) => {
                  if ([null, '[]'].includes(value)) {
                    callback('请填写完整');
                  } else {
                    callback();
                  }
                }
              });
            } else { // 设置这个表单项不是必填
              option.rules.push({
                required: false
              });
            }
          } else { // 联动开关关闭，那么这个表单项就是不必填的
            option.rules.push({
              required: false
            });
          }
        } else { // 不展示联动开关
          option.rules.push({
            required: field.required,
            message: messages('common.name.is.required', { name: field.fieldName })  // ${field.fieldName}必填)
          });
          if (field.required) {
            option.rules.push({
              validator: (rule, value, callback) => {
                if ([null, '[]'].includes(value)) {
                  callback('请填写完整');
                } else {
                  callback();
                }
              }
            });
          }
        }
      } else { // 不是公用列表
        option.rules.push({
          required: field.required,
          message: messages('common.name.is.required', { name: field.fieldName })  // ${field.fieldName}必填
        });
      }
      if (
        field.messageKey === 'employee_expand' &&
        !(field.fieldContent && (JSON.parse(field.fieldContent) || {}).messageKey === 'cust_list')
      ) {
        option.rules.push({
          max: 200,
          message: messages('common.max.characters.length', { max: 200 })
        });
      }
      if (field.messageKey === 'input') {
        option.rules.push({
          max: 50,
          message: messages('common.max.characters.length', { max: 50 })
        });
      }
      if (field.messageKey === 'title') {
        option.rules.push({
          max: 500,
          message: messages('common.max.characters.length', { max: 500 })
        });
      }
      if (field.messageKey === 'text_area') {
        option.rules.push({
          max: 1000,
          message: messages('common.max.characters.length', { max: 1000 })
        });
      }
      // 编辑模式不能修改申请人
      if (field.messageKey === 'applicant' && this.props.params.expenseReport) {
        field.isReadOnly = true;
      }
      if (field.messageKey === 'number') {
        if (field.fieldContent && JSON.parse(field.fieldContent)) {
          const fieldContentObject = JSON.parse(field.fieldContent);
          fieldNameHelp = fieldContentObject.unit ? `(${fieldContentObject.unit})` : '';
        }
      }
      let selectParticipantVisible = true;
      if (field.messageKey === 'select_participant' && field.fieldContent) {
        selectParticipantVisible = JSON.parse(field.fieldContent).isUse;
      }
      // const label = `${field.fieldName}${fieldNameHelp}`;
      const label = field.fieldTips && field.fieldTips.length > 0 ? <span>{field.fieldName}{fieldNameHelp}&nbsp;
      <Tooltip title={field.fieldTips}>
        <Icon type="question-circle-o" />
    </Tooltip>
  </span> : `${field.fieldName}${fieldNameHelp}`;
      return (
        field.fieldOID &&
        field.messageKey !== 'ying_fu_select_approver' &&
        field.messageKey !== 'end_date' &&
        selectParticipantVisible 
      ) && (
          <FormItem {...formItemLayout} label={label || ' '} key={field.fieldOID} colon={!!label}>
            {getFieldDecorator(field.fieldOID, option)(
              customField.renderForm({
                field,
                fieldDefaultValue,
                formDetail,
                copyValue: null,
                formValues: getFieldsValue(),
                type: 2,
                getPopupContainer: this.getPopupContainer,
                propsParams: {
                  formDataId: this.state.expenseReport ? this.state.expenseReport.id: null,
                  pkId: this.props.params.formDetail ? this.props.params.formDetail.id: null,
                  companyOID,
                  departmentOID
                },
                jobId: applicantJobId,
                jobInfo,
                onSwitchChange: this.onSwitchChange,
                applicantOID: expenseReport ? expenseReport.applicantOID : this.props.params.userOID,
                changeCompanyAndDepart: this.changeCompanyAndDepart
              })
            )}
          </FormItem>
        );
    });
  };

  // 控件之间联动关系
  formItemChange = (value) => {
    const { enableDepCompany } = this.props;
    const { formDetail, isInitDefaultValue, contractParams, associationContract } = this.state;
    const { companyOID, baseCurrency } = this.props.company;
    const _this = this
    if (isInitDefaultValue) return;
    const customFormFields = formDetail.customFormFields || [];
    customFormFields.some(item => {
      if (item.fieldOID === Object.keys(value)[0]) {
        let fieldConstraint = item.fieldConstraint ? JSON.parse(item.fieldConstraint) : {};
        if (item.messageKey === 'select_company' && fieldConstraint.unionCompany) {
          if (value[Object.keys(value)[0]].length > 0) {
            expenseReportService.getCostcenterByCompany(value[Object.keys(value)[0]][0].companyOID).then((res) => {
              customFormFields.map((item) => {
                if (item.messageKey === 'select_cost_center') {
                  if (res !== '' && res.data && res.data.costCenterItemOID) {
                    _this.props.form.setFieldsValue({ [item.fieldOID]: [{ costCenterItemOID: String(res.data.costCenterItemOID), name: res.data.name }] });
                  } else {
                    _this.props.form.setFieldsValue({ [item.fieldOID]: [] });
                  }
                  return true;
                }
              })
            });
          } else {
            customFormFields.map((item) => {
              if (item.messageKey === 'select_cost_center') {
                _this.props.form.setFieldsValue({ [item.fieldOID]: [] });
                return true;
              }
            })
          }

        }
      }
    });
    if (!(value && Object.prototype.toString.call(value) === '[object Object]')) return;
    customFormFields.map((item) => {
      if (item.fieldOID in value) {
        if (item.messageKey === 'select_department') {
          customFormFields.map((i) => {
            if (i.messageKey === 'select_cost_center' && !i.isReadOnly) {
              setTimeout(() => { firstInitLoad = true; }, 200);
              if (firstInitLoad) {
                this.setState({ loading: true });
                baseService.checkCostCenterNeedEmpty().then((res) => {
                  this.setState({ loading: false });
                  if (res.data.visible) {
                    i.clearDefault = true;
                    this.props.form.resetFields(i.fieldOID);
                  }
                });
              }
            }
          });
        }
        // 参与人部门权限控件
        if ((item.messageKey === 'select_department' || item.messageKey === 'select_cost_center')) {
          item.value = value[item.fieldOID];
          customFormFields.map((i) => {
            if (i.messageKey === 'select_participant') {
              setTimeout(() => {
                firstInitLoad = true;
              }, 200);
              if (firstInitLoad) {
                i.clearDefault = true;
              }
              const fieldContent = i.fieldContent ? JSON.parse(i.fieldContent) : { editable: true };
              if (!i.isReadOnly && fieldContent.editable) {
                this.props.form.resetFields(i.fieldOID);
              }
            }
          });
        }
        // 选择公司
        if (item.messageKey === 'select_company') {
          customFormFields.map((i) => {
            if (i.messageKey === 'select_cost_center' && !i.isReadOnly) {
              this.setState({ loading: true });
              baseService.checkCostCenterNeedEmpty().then((res) => {
                this.setState({ loading: false });
                if (res.data.visible) {
                  i.clearDefault = true;
                  // this.props.form.resetFields(i.fieldOID);
                  this.props.form.setFieldsValue({ [i.fieldOID]: undefined });
            }
              });
            }
            if (i.messageKey === 'select_department' && !i.isReadOnly && enableDepCompany === 'OPEN') {
              this.props.form.setFieldsValue({ [i.fieldOID]: undefined });
            }
          });
          // 清空收款单位
          const venMaster = customFormFields.filter(item => item.messageKey === 'venMaster')[0];
          if (venMaster) {
            this.props.form.resetFields(venMaster.fieldOID);
          }
          contractParams.companyOID = value[item.fieldOID] || companyOID;
          if (this.props.form.getFieldValue('contract') && associationContract.companyOID !== value[item.fieldOID]) {
            message.warning(messages('expense-parent-report.key191')/* 所选公司与关联的合同公司必须一致！*/);
            this.handleClearContract();
          }
        }
        // 收款人银行关联控件
        if (item.messageKey === 'payee' && value[item.fieldOID] && typeof value[item.fieldOID] === 'object') {
          item.value = value[item.fieldOID].key;
          customFormFields.map((i) => {
            if (i.messageKey === 'contact_bank_account') {
              const param = {
                userOID: value[item.fieldOID].key,
                page: 0,
                size: 20
              };
              let bank = { [i.fieldOID]: undefined };
              baseService.getUserBanks(param).then((res) => {
                const data = res.data;
                if (data && data.length > 0) {
                  data.map((item) => {
                    if (item.isPrimary) {
                      bank = {
                        [i.fieldOID]: [{
                          bankAccountNo: item.bankAccountNo,
                          originalBankAccountNo: item.originalBankAccountNo,
                          contactBankAccountOID: item.contactBankAccountOID
                        }]
                      };
                    }
                  });
                }
                this.props.form.setFieldsValue(bank);
              }).catch((e) => {
                this.props.form.setFieldsValue(bank);
              });
            }
          });
        }
        if (item.messageKey === 'select_cost_center') {
          if (item.dataSource && JSON.parse(item.dataSource || '{}').type === 'father') { // 父成本中心
            customFormFields.map((i) => {
              // 父成本中心修改时，子成本中心置空
              if (i.messageKey === 'select_cost_center' && i.dataSource && JSON.parse(i.dataSource || '{}').type === 'son') {
                this.props.form.setFieldsValue({ [i.fieldOID]: undefined });
              }
            });
          }
        }

        if (item.messageKey === 'currency_code') {
          contractParams.currency = value[item.fieldOID] || baseCurrency;
          this.setState({ contractParams });
          if (this.props.form.getFieldValue('contract') && associationContract.contractCurrency !== value[item.fieldOID]) {
            message.warning(messages('expense-parent-report.key192')/* “所选币种与关联的合同币种必须一致！*/);
            this.handleClearContract();
          }
        }
      }
    });
  };

  // 提交前检查组合控件的表单值验证,异步方法
  submitSaveValidateCombinationForm = () => {
    const { formDetail } = this.state;
    const customFormFields = formDetail.customFormFields || [];
    let isHaveValidate = false;
    const needValidateForms = ['venMasterSwitch', 'linkage_switch'];
    customFormFields.map((item) => {
      if (~needValidateForms.indexOf(item.messageKey)) {
        const info = this.props.form.getFieldValue(item.fieldOID);
        if (info) {
          info.callBackSubmit = !info.callBackSubmit;
          this.props.form.setFieldsValue({ [item.fieldOID]: info });
          isHaveValidate = true;
        }
      }
    });
    return isHaveValidate;
  };

  // 组合表单验证结果
  combinationFormValidateResult = () => {
    const { formDetail } = this.state;
    const customFormFields = formDetail.customFormFields || [];
    let isPassValid = true;
    const needValidateForms = ['venMasterSwitch', 'linkage_switch'];
    customFormFields.map((item) => {
      if (~needValidateForms.indexOf(item.messageKey)) {
        const info = this.props.form.getFieldValue(item.fieldOID);
        if (info) {
          isPassValid = !isPassValid || info.isPassValid;
        }
      }
    });
    return isPassValid;
  };

  handleSave = (e) => {
    e.preventDefault();
    if (this.submitSaveValidateCombinationForm()) {
      // 组合子表单验证信息传递需要时间
      setTimeout(this.delayHandleSave, 10);
    } else {
      this.delayHandleSave();
    }
  };

  /**
   * 格式化时间为UTC格式(YYYY-MM-DDTHH:mm:ssZ)
   * @param date: string(YYYY-MM-DD HH:mm:ss)
   * @returns {string}
   */
  formatDateToUtc = date => `${moment(date).utc().format('YYYY-MM-DDTHH:mm:ss')}Z`;

  // 判断是否需要重新计算补贴
  checkSubsidyChange = () => new Promise((resolve) => {
    this.setState({ submitting: true });
    const { expenseReport } = this.state;
    const { getFieldValue } = this.props.form;
    let dateFieldOID = null,
      startDate = null,
      endDate = null;
    // 新建报销单
    if (!expenseReport) {
      resolve(false);
      return;
    }
    (expenseReport.custFormValues || []).map((item) => {
      if (item.messageKey === 'start_date') {
        dateFieldOID = item.fieldOID;
      }
    });
    if (dateFieldOID && getFieldValue(dateFieldOID) && getFieldValue(dateFieldOID)[0]) {
      startDate = getFieldValue(dateFieldOID)[0].format('YYYY-MM-DD HH:mm:ss');
      endDate = getFieldValue(dateFieldOID)[1].format('YYYY-MM-DD HH:mm:ss');
    }
    if (startDate && endDate) {
      const params = {
        expenseReportOID: expenseReport.expenseReportOID,
        startDate: this.formatDateToUtc(startDate),
        endDate: this.formatDateToUtc(endDate)
      };
      if (expenseReport.recalculateSubsidy) {
        resolve(false);
      } else {
        expenseReportService.checkSubsidyChange(params).then((res) => {
          if (res.data) {
            Modal.confirm({
              title: messages('expense-parent-report.key218')/* 修改后，补贴费用将重新生成，是否继续*/,
              onOk: () => {
                expenseReport.recalculateSubsidy = true;
                this.setState({ expenseReport }, this.delayHandleSave);
              },
              onCancel: () => this.setState({ submitting: false })
            });
          }
          resolve(res.data);
        }).catch(() => {
          resolve(false);
        });
      }
    } else {
      expenseReport.recalculateSubsidy = false;
      this.setState({ expenseReport });
      resolve(false);
    }
  });

  delayHandleSave = () => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!this.combinationFormValidateResult()) {
        return;
      }
      const { applicantJobId } = this.props.params;
      const { formDetail, expenseReport, isMultiApplication } = this.state;
      const target = JSON.parse(JSON.stringify(expenseReport || formDetail));
      target.currencySame = this.checkFunctionProfiles('web.invoice.keep.consistent.with.expense', [true]);
      applicantJobId && applicantJobId !== ':applicantJobId' && (target.applicantJobId = applicantJobId);
      if (values.application) {
        target.applicationOID = values.application[0].applicationOID;
        if (isMultiApplication) { // 关联多申请单
          const expenseReportApplicationDTOS = [];
          values.application.map((item) => {
            expenseReportApplicationDTOS.push({
              applicationOID: item.applicationOID,
              tenantId: this.props.tenant.id
            });
          });
          target.expenseReportApplicationDTOS = expenseReportApplicationDTOS;
        }
      }

      if (values.contract) {
        target.contractHeaderId = values.contract[0].contractHeaderId;
      }
      let customFormFields = deepFullCopy(formDetail.customFormFields || []);
      if (expenseReport) {
        customFormFields = deepFullCopy(expenseReport.custFormValues || []);
      } else {
        target.remark = null;
      }
      if (!err) {
        const { expenseReportInvoices, formId, userOID, driverId, proxy } = this.props.params;
        const custFormValues = [];
        let canSubmit = true;
        Object.keys(values).map((key) => {
          customFormFields.map((field) => {
            if (key === field.fieldOID) {
              custFormValues.push(customField.formatFormValue(field, values[key]));
            }
          });
        });
        target.countersignApproverOIDs = this.props.form.getFieldsValue().addSign;
        target.custFormValues = custFormValues;
        if (driverId && driverId !== ':driverId') { // 代司机报销，增加driverId
          target.driverId = driverId;
          target.applicantOID = this.props.user.userOID // 代司机报销，申请人oid传秘书，但是表单的值用审批人oid去获取
        } else if (formId && userOID && userOID !== ':userOID') {
          target.applicantOID = userOID;
        }
        if (proxy === '1' && !target.driverId) { // 代上司报销，增加isProxy=1
          target.isProxy = 1
        }
        target.custFormValues.map((item, index) => {
          if (item.messageKey === 'select_cost_center') {
            try {
              item.value = JSON.parse(item.value)[0].costCenterItemOID;
            } catch (e) { }
            if (JSON.parse(item.dataSource || '{}').type === 'father' && item.value) { // 父成本中心
              target.custFormValues.map((subItem) => {
                // 如果选择了父成本中心，子成本中心不能为空
                if (subItem.messageKey === 'select_cost_center' && JSON.parse(subItem.dataSource || '{}').type === 'son' && !subItem.value) {
                  message.error(messages('common.please.select')/* 请选择*/ + subItem.fieldName);
                  canSubmit = false;
                }
              });
            }
          }
          if (item.messageKey === 'select_participant' && item.value) {
            const itemValue = JSON.parse(item.value);
            itemValue.map((user) => {
              this.state.requestParticipant.map((requestUser) => {
                if (user.userOID === requestUser.userOID) {
                  user.highOff = true;
                }
              });
            });
            item.value = JSON.stringify(itemValue);
          }
          // 保存前要将连选日期控件range_picker分为开始日期／结束日期控件
          if (item.messageKey === 'start_date') {
            customFormFields.map((fieldItem) => {
              if (fieldItem.messageKey === 'end_date') {
                const endDateItem = fieldItem;
                if (item.value) {
                  const rangePickerValue = deepFullCopy(item.value);
                  if (this.processEnableTime(item) && this.processEnableTime(fieldItem)) {
                    item.value = this.formatDateToUtc(rangePickerValue[0]);
                    endDateItem.value = this.formatDateToUtc(rangePickerValue[1]);
                  } else {
                    item.value = this.formatDateToUtc(moment(rangePickerValue[0]).format('YYYY-MM-DD 00:00:00'));
                    endDateItem.value = this.formatDateToUtc(moment(rangePickerValue[1]).format('YYYY-MM-DD 23:59:59'));
                  }
                }
                if (!item.value) {
                  item.value = undefined;
                  endDateItem.value = undefined;
                }
                target.custFormValues.splice(index + 1, 0, endDateItem);
              }
            });
          }
        });
        if (formDetail.customFormPropertyMap['report.property.associated.contract.enabled'] === 'true') {
          target.contractPosition = formDetail.customFormPropertyMap['report.property.associated.contract.config'];
        }
        target.expenseReportInvoices = expenseReportInvoices || [];
        if (!canSubmit) return;
        // 保存前需要先判断是否需要显示重新计算补贴的提示框
        this.checkSubsidyChange().then((res) => {
          if (!res) { // 不需要弹框，可以直接保存
            target.custFormValues.map((value, index) => {
              let fieldConstraint = value.fieldConstraint ? JSON.parse(value.fieldConstraint) : {};
              if (value.messageKey === 'select_company' && fieldConstraint.unionCompany) {
                target.custFormValues[index].value = target.custFormValues[index].value ? JSON.parse(target.custFormValues[index].value)[0].companyOID : null;
              }
              if (value.messageKey === 'select_cost_center' && value.isReadOnly) {
                target.custFormValues[index].value = target.custFormValues[index].value;
              }
              if (value.messageKey === 'public.assembly') {
                formDetail.customFormFields.map((field) => {
                  if (field.fieldOID === value.fieldOID) {
                    if (field.isHidden) {
                      if (!field.isSwitchOn) {
                        target.custFormValues[index].value = '[]';
                      }
                    }
                  }
                })
              }
            })
            this.setState({ submitting: true });
            // 新建报销单的recalculateSubsidy要置为true
            !expenseReport && (target.recalculateSubsidy = true);
            console.log('target', target, this.state.formDetail)
            let companyData = target.custFormValues.filter(value => {
              return value.fieldName === '费用承担公司';
            });
            let fujianData = target.custFormValues.filter(value => {
              return value.fieldName === '附件';
            });
            // console.log('companyData', companyData, this.state.companyInfo.companyOID)
            if (target.formCode === 'BX002' || target.formCode === 'BX001' || target.formCode === 'BX003' || target.formCode === 'BX004') {
              // if (companyData[0].value === this.state.companyInfo.companyOID && !fujianData[0].value) {
              //   message.warning('因您费用承担公司为MCML，请在附件中上传符合MCML DOA审批邮件');
              //   this.setState({ submitting: false });
              // } else {
                if (this.props.params.expenseReport && this.state.hasChangeCompanyAndDepart) {
                  confirm({
                    title: '提示',
                    content: '修改费用承担公司，费用承担部门，项目等操作，会自动清空费用分摊行，确认需要修改？',
                    okText: '确认',
                    onOk: () => {
                      expenseReportService.saveExpenseReport(target).then((res) => {
                        this.setState({ submitting: false });
                        message.success(res.data.draftToast || messages('common.save.success', { name: '' }));
                        if (expenseReport) {
                          this.props.close({ refresh: true, refreshAccount: !!res.data.draftToast });
                        } else {
                          menuRoute.goForm(this, res.data.formCode, {
                            action: 'detail',
                            params: {
                              pageFrom: 'my',
                              expenseReportOID:res.data.expenseReportOID
                            }
                          })
                        }
                      }).catch((error) => {
                        console.error(error)
                        this.setState({ submitting: false });
                        message.error(error.response.data.message);
                      });
                    },
                    onCancel: () => {
                      this.setState({ submitting: false });
                    }
                  })
                } else {
                  expenseReportService.saveExpenseReport(target).then((res) => {
                    this.setState({ submitting: false });
                    message.success(res.data.draftToast || messages('common.save.success', { name: '' }));
                    if (expenseReport) {
                      this.props.close({ refresh: true, refreshAccount: !!res.data.draftToast });
                    } else {
                      menuRoute.goForm(this, target.formCode, {
                        action: 'detail',
                        params: {
                          pageFrom: 'my',
                          expenseReportOID: res.data.expenseReportOID
                        }
                      })
                    }
                  }).catch((error) => {
                    console.error(error)
                    this.setState({ submitting: false });
                    message.error(error.response.data.message);
                  });
                }
              // }
            } else {
              expenseReportService.saveExpenseReport(target).then((res) => {
                this.setState({ submitting: false });
                message.success(res.data.draftToast || messages('common.save.success', { name: '' }));
                if (expenseReport) {
                  this.props.close({ refresh: true, refreshAccount: !!res.data.draftToast });
                } else {
                  menuRoute.goForm(this, target.formCode, {
                    action: 'detail',
                    params: {
                      pageFrom: 'my',
                      expenseReportOID: res.data.expenseReportOID
                    }
                  })
                }
              }).catch((error) => {
                console.error(error)
                this.setState({ submitting: false });
                message.error(error.response.data.message);
              });
            }
          }
        });
      } else {
        let costCenterFalse = false;
        Object.keys(values).map((key) => {
          customFormFields.map((fields) => {
            if (fields.messageKey === 'select_cost_center' && fields.isReadOnly) {
              if (key === fields.fieldOID) {
                if (!values[key]) {
                  costCenterFalse = true;
                }
              }
            }
          });
        });
        if (costCenterFalse) {
          message.error(messages('common.error')/* 请联系管理员*/);
        }
      }
    });
  };

  // 是否可以审批加签
  isCounterSignEnable = (formOID) => {
    expenseReportService.isCounterSignEnable(this.props.company.companyOID, formOID, 'enableAddSignForSubmitter').then((res) => {
      this.setState({
        signEnable: res.data.enabled,
        approvalAddSignScope: res.data.approvalAddSignScope.companyOIDs
      });
    });
  };

  // 修改关联申请单
  handleChangeApplication = (result) => {
    const { applicantJobId } = this.props.params;
    const { formDetail, formDefaultValue } = this.state;
    this.setState({ loading: true });
    // 处理申请单自定义表单值带入报销单自定义表单值
    if (result && result.length > 0) {
      const applicationOIDs = [];
      result.map(item => applicationOIDs.push(item.applicationOID));
      // 需求12562 报销单创建时，可以关联多申请单
      const jobId = applicantJobId === ':applicantJobId' ? undefined : applicantJobId;
      expenseReportService.getMultiApplicationInfo(applicationOIDs, jobId).then((res) => {
        this.setState({ loading: false, isInitDefaultValue: true });
        const applicationFieldDefaultValues = res.data || [];
        const customFormFields = deepFullCopy(formDetail.customFormFields || []);
        // 有默认值且当前选择的是默认值时，不带入关联申请单控件值的控件
        const hasDefaultNotChange = ['select_corporation_entity', 'select_company', 'select_department'];
        customFormFields.map((field) => {
          applicationFieldDefaultValues.map((item) => {
            const { getFieldsValue, getFieldValue } = this.props.form;
            let value = '';
            let fieldDefaultValue;
            if (getFieldsValue().hasOwnProperty(field.fieldOID)) {
              value = getFieldValue(field.fieldOID);
            }
            if (field.messageKey === 'start_date') {
              field.messageKey = 'range_picker';
            }
            if (item.messageKey === 'start_date') {
              applicationFieldDefaultValues.map((subItem) => {
                if (subItem.messageKey === 'end_date') {
                  item.messageKey = 'range_picker';
                  item.showValue = [moment(item.value), moment(subItem.value)];
                }
              });
            }
            formDefaultValue.map((formItem) => {
              formItem.fieldOID === field.fieldOID && (fieldDefaultValue = customField.getDefaultValue(field, formItem));
            });
            if (
              item.messageKey === field.messageKey &&
              value !== item.value &&
              field.fieldOID === item.fieldOID &&
              item.messageKey !== 'end_date'
            ) {
              const setValue = (valueItem) => {
                const applicationDefaultCustom = valueItem;
                applicationDefaultCustom.name = applicationDefaultCustom.showValue;
                applicationDefaultCustom.fieldConstraint = field.fieldConstraint;
                applicationDefaultCustom.fieldContent = field.fieldContent;
                let defaultValue = customField.getDefaultValue(field, applicationDefaultCustom) || customField.getInitialValue(applicationDefaultCustom);
                if (field.messageKey === 'select_department') { // fix bug 26352
                  defaultValue = [{
                    [this.checkFunctionProfiles('department.full.path.disabled', [true]) ? 'name' : 'path']: applicationDefaultCustom.name,
                    departmentOid: applicationDefaultCustom.value
                  }];
                }
                if (field.messageKey === 'select_company') { // 若公司组件的noDefault为true，customField.getDefaultValue()返回undefined
                  const fieldConstraint = JSON.parse(field.fieldConstraint || '{}');
                  fieldConstraint.noDefault = false;
                  field.fieldConstraint = JSON.stringify(fieldConstraint);
                  defaultValue = customField.getDefaultValue(field, applicationDefaultCustom);
                }
                defaultValue && this.props.form.setFieldsValue({ [field.fieldOID]: defaultValue });
              };
              if (field.messageKey === 'select_participant') {
                this.setState({ requestParticipant: JSON.parse(item.value || '[]') });
              }
              if (~hasDefaultNotChange.indexOf(field.messageKey) && fieldDefaultValue && value) { // 有默认值且当前选择的是默认值时，不带入关联申请单控件值
                if (
                  (field.messageKey === 'select_corporation_entity' && fieldDefaultValue[0] && value !== fieldDefaultValue[0].companyReceiptedOID) ||
                  (field.messageKey === 'select_department' && fieldDefaultValue[0] && value !== fieldDefaultValue[0].departmentOid) ||
                  (field.messageKey === 'select_company' && value !== fieldDefaultValue.key && value.key !== fieldDefaultValue.key)
                ) {
                  setValue(item);
                }
              } else {
                setValue(item);
              }
            }
          });
        });
        this.setState({ isInitDefaultValue: false });
      });
    } else {
      this.setState({ loading: false });
    }
  };

  handleChangeContract = (contract) => {
    const { contractParams } = this.state;
    this.setState({ associationContract: { ...contract[0], ...contractParams } });
  };

  handleClearContract = () => {
    this.props.form.setFieldsValue({ contract: void 0 });
    this.setState({ associationContract: {} });
  };

  // 查询报销单是否可关联多申请单
  checkRelatedApplication = () => {
    expenseReportService.checkRelatedApplication(this.props.params.formId).then((res) => {
      this.setState({ isMultiApplication: res.data });
    });
  };

  // 返回
  goBack = () => {
    const expenseReport = this.props.params.expenseReport;
    if (expenseReport) {
      this.props.close();
      (expenseReport.custFormValues || []).map((item) => {
        this.props.form.setFieldsValue({ [item.fieldOID]: customField.getInitialValue(item) });
      });
    } else {
      // this.context.router.push(menuRoute.getRouteItem('expense-report').url);
      menuRoute.goBack(this)
    }
  };

  getCompanies = () => {
    expenseReportService.getCompanies().then(res => {
      // console.log('res', res)
      res.data && res.data.map(e => {
        if (e.companyCode === '145') {
          this.setState({
            companyInfo: e
          });
        }
      })
    });
  };

  changeCompanyAndDepart = () => {
    // console.log("this.state.hasChange", this.state.hasChange)
    if (this.state.hasChange) {
      this.setState({ hasChangeCompanyAndDepart: true })
    }
  }

  render() {
    const { loading, formDetail, submitting, signEnable, approvalAddSignScope, isMultiApplication, expenseReport, contractParams } = this.state;
    const { applicationOID } = this.props.params;
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: !expenseReport ? 10 : 14, offset: 1 },
    };
    const signPerson = [];
    expenseReport && expenseReport.countersignApproverNames && expenseReport.countersignApproverNames.map((item) => {
      signPerson.push({ userOID: item.userOID, fullName: item.fullName });
    });
    const companyDTOS = approvalAddSignScope.length ? approvalAddSignScope : null;
    const signName = customField.getSignNameForSubmitter(formDetail && formDetail.customFormPropertyMap);
    return (
      <div className="new-expense-report" ref="newExpenseReport">
        {!expenseReport && <div className="form-name">{formDetail.formName}</div>}
        <Form onSubmit={this.handleSave}>
          <FormItem {...formItemLayout} label=" " colon={false}>
            {customField.instructionsTag(formDetail.customFormPropertyMap)}
          </FormItem>
          {(!expenseReport && (formDetail.formType === 3002 || formDetail.formType === 3003)) && (
            <FormItem {...formItemLayout} label={messages('expense-parent-report.key61'/* 关联申请单*/)}>
              {getFieldDecorator('application', {
                rules: [{
                  required: true,
                  message: messages('common.name.is.required', { name: messages('expense-parent-report.key61'/* 关联申请单*/) })
                }]
              })(
                <Chooser
                  type="my_request"
                  listExtraParams={{ formOID: this.props.params.formId, userOID: this.props.user.userOID }}
                  labelKey="businessCode"
                  valueKey="applicationOID"
                  disabled={applicationOID !== ':applicationOID' && !!applicationOID}
                  itemMap
                  single={!isMultiApplication} // 需求12562 报销单创建时，可以关联多申请单
                  onChange={this.handleChangeApplication} />
              )}
            </FormItem>
          )}
          {
            !expenseReport
            && formDetail.customFormPropertyMap
            && formDetail.customFormPropertyMap['report.property.associated.contract.enabled'] === 'true'
            && formDetail.customFormPropertyMap['report.property.associated.contract.config'] === 'DOCUMENTS_HEAD'
            && <FormItem {...formItemLayout} label={messages('expense-parent-report.key193')/* 关联合同*/}>
              {getFieldDecorator('contract', {
                rules: [{
                  required: false,
                  message: messages('common.name.is.required', { name: messages('expense-parent-report.key193')/* 关联合同*/ })
                }]
              })(
                <Chooser
                  type="contract"
                  listExtraParams={{
                    documentType: 'PUBLIC_REPORT',
                    ...contractParams
                  }}
                  labelKey="contractNumber"
                  valueKey="contractHeaderId"
                  itemMap
                  onChange={this.handleChangeContract}
                  single />
              )}
            </FormItem>
          }
          <Spin spinning={loading}>
            {this.renderFormItem()}
          </Spin>
          {/* {signEnable && (
            <FormItem {...formItemLayout} label={signName} key="addSign">
              {getFieldDecorator('addSign', {
                rules: [{
                  required: formDetail.customFormPropertyMap && formDetail.customFormPropertyMap.enableCounterSignForSubmitterMustWriter === 'true',
                  message: messages('common.can.not.be.empty', { name: signName })
                }],
                initialValue: signPerson
              })(
                <Chooser
                  selectorItem={(function () {
                    const chooserItemUser = deepFullCopy(chooserData.user);
                    chooserItemUser.title = signName;
                    return chooserItemUser;
                  }(this))}
                  valueKey="userOID"
                  labelKey="fullName"
                  onlyNeed="userOID"
                  listExtraParams={{ corporationOID: companyDTOS, roleType: 'TENANT', companyOID: companyDTOS }}
                  showArrow={formDetail.customFormPropertyMap && formDetail.customFormPropertyMap.countersignType === '2'}
                  newline />
              )}
            </FormItem>
          )} */}
          <div className={expenseReport ? 'slide-footer' : 'buttons'}>
            <Button type="primary" htmlType="submit" loading={submitting} className="button-new">
              {expenseReport ? messages('finance-setting.key137')/* 确认*/ : messages('common.create')/* 新建*/}
            </Button>
            <Button onClick={this.goBack}>{messages('common.cancel')/* 取消*/}</Button>
          </div>
        </Form>
      </div>
    );
  }
}

NewExpenseReport.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    user: state.login.user,
    language: state.main.language,
    company: state.login.company,
    tenant: state.login.tenant,
    enableDepCompany: state.setting.enableDepCompany,
  };
}

NewExpenseReport.propTypes = {
  expenseReport: React.PropTypes.object
};

const WrappedNewExpenseReport = Form.create({
  onValuesChange(props, values) {
    newExpenseReportThis.formItemChange(values);
  },
})(NewExpenseReport);

export default connect(mapStateToProps)(WrappedNewExpenseReport);
